package com.example.demo02.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo02.common.Result;
import com.example.demo02.entity.Customer;
import com.example.demo02.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @PostMapping("/add")
    public Result add(@RequestBody Customer customer) {
        try {
            customerService.save(customer);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Customer customer) {
        customerService.updateById(customer);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        customerService.removeById(id);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Customer> customerList = customerService.list();
        return Result.success(customerList);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Customer customer = customerService.getById(id);
        return Result.success(customer);
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(required = false) String name) {
        Page<Customer> page = customerService.page(new Page<>(pageNum, pageSize),
                new QueryWrapper<Customer>().like(StrUtil.isNotBlank(name), "name", name));
        return Result.success(page);
    }
}